/*
 * rampdowntimer.c
 *
 *  Created on: 2015-04-09
 *      Author: atreyu
 */

#include "rampdowntimer.h"

int grnFlip=0;
unsigned long ulPeriod;

void initTimer3(void)
{
	ROM_SysCtlPeripheralEnable(SYSCTL_PERIPH_TIMER3);
	//set timer period: 40MHz/10/2 = 2MHz = 0.5us
	//for 1000us = 1ms use Div by 0.1 and then 4, 40MHz / 0.1 / 4 = 1ms
	ROM_TimerConfigure(TIMER3_BASE, TIMER_CFG_PERIODIC);
	ulPeriod = ROM_SysCtlClockGet()/200;
	ROM_TimerLoadSet(TIMER3_BASE, TIMER_A, ulPeriod - 1);

	//Timer interrupt setup
	ROM_TimerIntClear(TIMER3_BASE, TIMER_TIMA_TIMEOUT);
	ROM_TimerIntEnable(TIMER3_BASE, TIMER_TIMA_TIMEOUT);
	ROM_IntEnable(INT_TIMER3A);
	ROM_TimerEnable(TIMER3_BASE, TIMER_A);
	bt_UARTsend("Init Timer3");
	loading_bar(24);
	load_okfail(1);
}

void timer3Handler(void)
{
	//reset counter value back to ulPeriod
	if(rampdown_condition == 0)
		ROM_TimerLoadSet(TIMER3_BASE, TIMER_A, ulPeriod-1);
	//only re-enable timer if dont get new part, so have to use one of the lasers as an indicator flag
	else if(rampdown_condition == 1)
	{
		bt_UARTsend("\r\nRamping down\r\n");
		ROM_TimerLoadSet(TIMER3_BASE, TIMER_A, 10000);		//set this to 5 seconds or something
	}


	//clear interrupt
	if(rampdown_condition == 0 || ramp_hit == 1)		//XXXXXX MUST ADD ramp_hit TO reflect laser
	{
		ROM_TimerIntClear(TIMER3_BASE, TIMER_TIMA_TIMEOUT);
	}

	if(ramp_hit == 0 && rampdown_condition == 1)
		belt_driver(0);

	if(ramp_hit == 1) ramp_hit = 0;

	//bt_UARTsend("timer\n");
	grnFlip ^= 0xff;
	ROM_GPIOPinWrite(GPIO_PORTF_BASE, grnled, grnFlip);
}
